package controllers;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class MessageServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		UserService userService = UserServiceFactory.getUserService();
		String thisURL = request.getRequestURI();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String type = URLDecoder.decode(path.toLowerCase().replaceAll("/msg/", ""),"UTF-8");
		
		String title = "Message";
		String msg = "<a href=\"/home\">Go to home</a>";
		
		if (type != null && type.equalsIgnoreCase("not-permission")) {
			msg = "Sorry, you don't enought permission access this page! Please go back or go to <a href=\"/home\">home</a>";
		}
		
		if (type != null && type.equalsIgnoreCase("page-not-found")) {
			title = "Page Not Found";
			msg = "Sorry, this page is not exists! Please go back or go to <a href=\"/home\">home</a>";
		}
		
		if (type != null && type.equalsIgnoreCase("blacklist")) {
			title = "Page Not Found";
			msg = "Sorry, this website is in my blacklist. Please go back or go to <a href=\"/home\">home</a>";
		}
		
		if (type != null && type.equalsIgnoreCase("payment-success")) {
			msg = "You has been purchased success! We will check payment and notify for you later. Thank! <br /> <a href=\"/home\">Go to home</a>";
		}
		
		if (type != null && type.equalsIgnoreCase("update-profile")) {
			msg = "You need to update your information before on other sites. Update profile <a href=\"/register\">here</a>";
		}
		
		if (type != null && type.equalsIgnoreCase("login-success")) {
			if (request.getUserPrincipal() != null) {
				String username = request.getUserPrincipal().getName();
				String url = userService.createLogoutURL(thisURL);
				
				msg = "Thank you! You have been login with user account '" + username + "'. You can <a href=\"" + url + "\">sign out</a>";
			} else {
				String url = userService.createLoginURL(thisURL);
				msg = "Please <a href=\"" + url + "\">sign in</a>";
			}
		}
		
		if (type != null && type.equalsIgnoreCase("logout-success")) {
			String url = userService.createLoginURL(thisURL);
			msg = "Thank you! You have been logout success. You can <a href=\"" + url + "\">login here</a>";
		}
		
		
		request.setAttribute("title", title);
		request.setAttribute("msg", msg);
		try {
			request.getRequestDispatcher("/pages/message.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
